<template>
  <div>
    <!-- 搜索框 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchModel" size="mini">
        <el-row type="flex" justify="space-between" align="middle">
          <el-col :span="20">
            <el-form-item label="客户名称">
              <el-input v-model="searchModel.keyword" placeholder="请输入客户名" clearable style="width: 180px">
              </el-input>
            </el-form-item>
            <el-form-item label="维护人">
              <el-select v-model="searchModel.uid" filterable clearable placeholder="请选择维护人" style="width: 180px">
                <el-option v-for="item in searchModel.userList" :key="item.id" :label="item.username" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="添加人">
              <el-select v-model="searchModel.add_uid" filterable clearable placeholder="请选择添加人" style="width: 180px">
                <el-option v-for="item in searchModel.userList" :key="item.id" :label="item.username" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="queryCustomers" icon="el-icon-search" round>查询</el-button>
              <el-button size="mini" @click="resetSearch" icon="el-icon-refresh-left" round>重置</el-button>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <div class="operation-buttons">
              <el-button type="success" size="mini" @click="downloadFile('审计-所有客户.xlsx')" v-if="downloadShow"
                round>导出客户</el-button>
              <router-link to="/client/addClient">
                <el-button type="success" size="mini" round>新增客户</el-button>
              </router-link>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="clientList" stripe style="width: 100%"
        :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
        <el-table-column prop="name" label="客户名称" min-width="200">
        </el-table-column>
        <el-table-column prop="" label="重点客户" width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.is_key == 1" type="danger" size="mini">重点客户</el-tag>
            <el-tag v-else size="mini">非重点客户</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="user_name" label="维护人" width="120">
        </el-table-column>
        <el-table-column prop="contacts.name" label="联系人" width="120">
        </el-table-column>
        <el-table-column prop="contacts.department" label="联系人部门" width="120">
        </el-table-column>
        <el-table-column prop="add_name" label="添加人" width="120">
        </el-table-column>

        <el-table-column label="操作" align="right" width="280">
          <template slot-scope="scope">
            <el-button-group>
              <el-button size="mini" type="primary" @click="viewDetail(scope.row)" round>详情</el-button>
              <el-button size="mini" type="warning" @click="editClient(scope.row)" round>修改</el-button>
              <el-button size="mini" type="success" @click="viewContract(scope.row)" round>合同</el-button>
              <el-button size="mini" type="danger" v-if="scope.row.isRemovable" @click="deleteClient(scope.row)"
                round>删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination class="pagination" @current-change="handleCurrentChange" :current-page="searchModel.pageNo"
        :page-size="pagesize" :total="total" :pager-count="5" layout="total, prev, pager, next">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import clientApi from '@/api/client'
import axios from 'axios';
import { getToken } from '@/utils/auth'

export default {
  name: 'clientIndex',
  data() {
    return {
      searchModel: {
        pageNo: 1,
        add_uid: '',
        keyword: '',
        uid: '',
        userList: [],
      },
      clientList: [],
      total: 0,
      pagesize: 10,
      downloadShow: false,


    }
  },
  methods: {
    downloadFile(fileName) {
      const fileUrl = '/client_download'; // 文件的URL地址

      axios.get(fileUrl, { responseType: 'blob', headers: { 'Authorization': 'Bearer ' + getToken() } })
        .then(response => {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();
        })
        .catch(error => {
          console.error(error);
        });
    },
    //删除客户
    deleteClient(client) {
      this.$confirm(`此操作将删除 ${client.name}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        clientApi.deleteClient(client.id).then(response => {
          this.$message({
            type: 'success',
            message: response.message
          });
          this.getClientList();
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },

    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo;
      this.getClientList();
    },
    //获取下拉框用户
    getUidList() {
      clientApi.getUidList().then(response => {
        this.searchModel.userList = response.data;
      })
    },
    //搜索客户
    queryCustomers() {
      this.searchModel.pageNo = 1;
      this.getClientList();
    },
    //获取客户列表
    getClientList() {
      clientApi.getClientList(this.searchModel).then(response => {
        this.clientList = response.data.list.data;
        this.total = response.data.list.total;
        this.pagesize = response.data.list.per_page;
        this.downloadShow = response.data.downloadShow;
      })
    },
    // 重置搜索
    resetSearch() {
      this.searchModel = {
        pageNo: 1,
        add_uid: '',
        username: '',
        uid: '',
        userList: this.searchModel.userList
      };
      this.getClientList();
    },

    // 查看详情
    viewDetail(row) {
      this.$router.push({ path: '/client/detail', query: { id: row.id } });
    },

    // 编辑客户
    editClient(row) {
      this.$router.push({ path: '/client/addClient', query: { id: row.id } });
    },

    // 查看合同
    viewContract(row) {
      this.$router.push({ path: '/contract/contractIndex', query: { clientID: row.id } });
    }
  },
  created() {
    this.getUidList();
    this.getClientList();

    // 监听路由变化，如果是从添加页返回则刷新
    this.$watch(
      () => this.$route.query.refresh,
      (newVal) => {
        if (newVal === 'true') {
          this.getClientList(); // 刷新数据
          // 清除参数，避免重复刷新
          this.$router.replace({ query: {} });
        }
      }
    );
  },


}
</script>

<style>
.search-card {
  margin-bottom: 16px;
}

.search-card .el-form--inline .el-form-item {
  margin-right: 10px;
}

.search-card .el-form-item {
  margin-bottom: 0;
}

.search-card .el-card__body {
  padding: 15px 20px;
}

.operation-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.operation-buttons .el-button {
  margin-left: 0;
}

.table-card {
  margin-bottom: 16px;
}

.table-card .el-card__body {
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

/* 表格内按钮组样式 */
.el-button-group .el-button--mini {
  padding: 7px 10px;
}

.el-button-group .el-button+.el-button {
  margin-left: 6px;
}

.search-card .el-form-item__label {
  padding-right: 8px;
}
</style>